import {
  login as netLogin,
  GetRoleExtraPerm,
  UpdatedFailLogins,
} from '@/network/login.js';
import router from '@/router';
import { setTimeToken } from '@/utils/auth.js';
import { ElMessage } from 'element-plus';
import { GM_SM4Decrypt, GM_SM4Encrypt } from '../../utils/sm4Import';

export default {
  namespaced: true,
  state: () => ({
    token: localStorage.getItem('token') || '',
    menuType: true,
    userInfo: localStorage.getItem('userInfo') || {},
    path: localStorage.getItem('path') || '/users',
    //zgq
    RoleExtraPerm: sessionStorage.getItem('roleExtraPer') || '',
    role: localStorage.getItem('RoleCode') || '',
    // zxf---------------------------------------------------
    // 保存用户信息
    userInfoVx: {
      UserCode: localStorage.getItem('UserCode') || '',
      RoleCode: localStorage.getItem('RoleCode') || '',
      WorkCode: localStorage.getItem('WorkCode') || '',
      Name: localStorage.getItem('Name') || '',
      cityCode: localStorage.getItem('userCityCode') || -1,
      venueCode: localStorage.getItem('userVenueCode') || -1,
    },
    // new 保存信息改变的数据
    ACVCodesVx: {
      activityCode: localStorage.getItem('ActivityCode') || -1,
      cityCode: localStorage.getItem('CityCode') || -1,
      venueCode: localStorage.getItem('VenueCode') || -1,
      selectType: 'selectVenue',
    },
    cityNameVx: localStorage.getItem('CityName') || '',
    // ----------------------------------------------------zxf
  }),
  mutations: {
    setToken(state, payload) {
      state.token = payload;
      localStorage.setItem('token', payload);
    },
    setUser(state, payload) {
      state.userInfo = payload;
      localStorage.setItem('userInfo', JSON.stringify(payload));
    },
    changeMenuType(state) {
      state.menuType = !state.menuType;
    },
    setPath(state, payload) {
      state.path = payload;
      localStorage.setItem('path', payload);
    },
    //zgq
    //------------------获取角色增删改查权限
    setRole(state, payload) {
      state.role = payload;
      sessionStorage.setItem('role', payload);
    },
    saveRoleExtraPerm(state, payload) {
      state.RoleExtraPerm = payload;
      sessionStorage.setItem('roleExtraPer', JSON.stringify(payload));
    },
    // ---------------------------------
    // zxf---------------------------
    saveUserInfo(state, payload) {
      // console.log(state, payload)
      state.userInfoVx.WorkCode = payload?.WorkCode;
      state.userInfoVx.Name = payload?.Name;
      state.userInfoVx.cityCode = payload?.CityCode;
      state.userInfoVx.UserCode = payload?.Code;
      state.userInfoVx.RoleCode = payload?.Type;

      let venue = payload?.VenuesCode == null ? -1 : payload?.VenuesCode;
      state.userInfoVx.venueCode = venue;
      localStorage.setItem('WorkCode', payload?.WorkCode);
      localStorage.setItem('Name', payload?.Name);
      localStorage.setItem('userCityCode', payload?.CityCode);
      localStorage.setItem('userVenueCode', venue);
      localStorage.setItem('UserCode', payload?.Code);
      localStorage.setItem('RoleCode', payload?.Type);
      // console.log(state.userInfoVx)
    },
    saveACVCodes(state, payload) {
      // new
      state.ACVCodesVx.activityCode = payload?.ActivityCode;
      state.ACVCodesVx.cityCode = payload?.CityCode;
      let venue = payload?.VenuesCode == null ? -1 : payload?.VenuesCode;
      state.ACVCodesVx.venueCode = venue;
      localStorage.setItem('ActivityCode', payload?.ActivityCode);
      localStorage.setItem('CityCode', payload?.CityCode);
      localStorage.setItem('VenueCode', venue);
    },
    setACVCodes(state, payload) {
      // new
      // console.log(payload)
      state.ACVCodesVx.cityCode = payload?.cityCode;
      state.ACVCodesVx.venueCode = payload?.venueCode;
      state.ACVCodesVx.selectType = payload?.type;
      // console.log(state.ACVCodesVx)
    },
    getCity(state, payload) {
      state.cityNameVx = payload.CityName == null ? '' : payload.CityName;
      localStorage.setItem('CityName', state.cityNameVx);
    },
    // ---------------------------------zxf
  },
  actions: {
    //登录
    login({ commit }, payload) {
      return new Promise((resolve, reject) => {
        netLogin(payload)
          .then((result) => {
            let paramsStrDec = JSON.parse(GM_SM4Decrypt(paramsStr));
            console.table(result)
            // console.log(paramsStrDec.roleArr)
            // 获取配置文件角色数组，判断此角色是否可以登陆
            let type = result?.user?.Type;
            let isExistLoginRole = paramsStrDec.roleArr.includes(Number(type));
            // console.log(isExistLoginRole)
            if (isExistLoginRole) {
              // console.log(paramsStrDec)
              // console.log("app", result,paramsStrDec.failLogins);
              // 获取配置文件中的最大登录失败次数
              let getFailLogins = paramsStrDec.failLogins;
              if (result.user.FailLogins <= getFailLogins) {
                commit('setToken', result.token.token);
                commit('setUser', result.user);
                // zxf--------------------------------保存用户及城市和活动编码
                commit('saveUserInfo', result.user);
                commit('saveACVCodes', result.user);
                commit('getCity', result.user);
                // --------------------------------zxf
                // zgq
                // --------------------------------
                setTimeToken();
                commit('setRole', result.user.Type);
                GetRoleExtraPerm({ role: Number(result.user.Type) })
                  .then((result) => {
                    commit('saveRoleExtraPerm', result);
                  })
                  .catch((err) => {
                    console.log(err);
                  });
                router.replace('/home');
                resolve();
              } else {
                ElMessage({ message: '登录次数过多请联系管理员！', type: 'warning' });
              }
            } else {
              ElMessage({ message: '此角色不能登录！', type: 'warning' });
            }
          })
          .catch((err) => {
            // console.log(err)
            // console.log(typeof err)
            // console.log(String(err))
            if (typeof err == 'string' && err.indexOf('ECONNREFUSED') != -1) {
              ElMessage({
                message: 'ECONNREFUSED,服务断开！',
                type: 'warning',
              });
            } else if (
              typeof err == 'object' &&
              String(err).indexOf('密码错误') != -1
            ) {
              ElMessage({ message: err, type: 'warning' });
            } else if (
              typeof err == 'object' &&
              String(err).indexOf('登录次数过多') != -1
            ) {
              ElMessage({ message: err, type: 'warning' });
            } else {
              ElMessage({ message: '其他错误！', type: 'warning' });
            }
            // console.log(err.message)
            // // 这里当密码错误时更新登录失败次数
            // if (err.message == '密码错误！') {
            //   ElMessage({ message: err.message, type: 'warning', })
            //   // console.log(payload)
            //   // UpdatedFailLogins({ workCode: payload.WorkCode, }).then((res) => {
            //   //   ElMessage({ message: err, type: 'warning', })
            //   // }).catch((err) => {
            //   //   console.log(err);
            //   // });
            // }
            reject(err);
          });
      });
    },
    //退出
    logout({ rootState, commit }) {
      commit('setToken', '');
      // 登出清除vuex -- app
      localStorage.clear();
      sessionStorage.clear();
      router.replace('/');
      location.reload();
    },
    getCity(context, payload) {
      // console.log(payload+"Action")
      context.commit('getCity', payload);
    },
    getRoleExtraPerm(context, payload) {
      context.commit('saveRoleExtraPerm', payload);
    },
    async setRolePers(context, payload) {
      await GetRoleExtraPerm({ role: payload })
        .then((result) => {
          // console.info('saveRoleExtraPerm', result);
          context.commit('saveRoleExtraPerm', result);
          //如果是修改权限页面本身则进行本业刷新
          // let ary = Array.from(result);
          // let xx = ary.join(',');
          // console.info(xx, xx.indexOf('btn-role'), 'aaaa');
          // if (xx.indexOf('btn-role') > -1) {
          //   // location.reload();
          // }
        })
        .catch((err) => {
          console.error(err);
        });
    },
    setACVCodes({ commit }, payload) {
      commit('setACVCodes', payload);
    },
  },
};
